package mainFragment.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import common.BaseActivity;
import common.BaseFragmentAdapter;
import common.Constant;
import https.InterNetController;
import https.handler.ErrorPageHandler;
import mainFragment.bean.AdminssionBean;
import mainFragment.bean.CollegeIndexBean;
import topic.bean.TopicGroupBean;
import mainFragment.bean.ZhaoShengMessageBean;
import mainFragment.fragment.CollegeIntroduce;
import mainFragment.fragment.OnLineAsk;
import mainFragment.fragment.TopicGroup;
import mainFragment.fragment.ZhaoShengMessageListView;
import mainFragment.fragment.ZhaoShengSituation;
import view.MyImageLoader;
import view.MyPagerSlidingTabStrip;
import view.MyToFourFragmentDialog;
import view.MyVolunteerScrollView;
import view.MyVolunteerScrollViewListener;

/**
 * Created by Administrator on 2017/2/27.
 * 高校主页
 */


@ContentView(R.layout.college_index)
public class CollegeIndex extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.college_index_back)
    private ImageView college_index_back;
    @ViewInject(R.id.college_index_school_ima)
    private ImageView college_index_school_ima;//学校图片
    @ViewInject(R.id.college_index_icon)
    private ImageView college_index_icon;//校徽
    @ViewInject(R.id.college_name)
    private TextView college_name;//校名
    @ViewInject(R.id.college_index_header_layout_parent)
    private LinearLayout college_index_header_layout_parent;
    @ViewInject(R.id.college_index_header_layout)
    private LinearLayout college_index_header_layout;
    @ViewInject(R.id.college_index_focus)
    private Button college_index_focus;//关注
    @ViewInject(R.id.college_index_strip)
    private MyPagerSlidingTabStrip college_index_strip;
    @ViewInject(R.id.college_index_pager)
    private ViewPager college_index_pager;
    @ViewInject(R.id.college_index_scroll)
    private MyVolunteerScrollView college_index_scroll;
    @ViewInject(R.id.college_index_header)
    private RelativeLayout college_index_header;//上滑出现的头部
    @ViewInject(R.id.college_index_name)
    private TextView college_index_name;
    private android.support.v4.app.FragmentManager fragmentManager;
    private BaseFragmentAdapter baseFragmentAdapter;
    private String[] tabs = new String[]{"在线提问", "学校简介", "招生信息", "招生情况", "讨论小组"};
    private OnLineAsk fg1;
    private CollegeIntroduce fg2;
    private ZhaoShengMessageListView fg3;
    private ZhaoShengSituation fg4;
    private TopicGroup fg5;
    private String id;//当前高校id
    private int scrollDistance;//可以滑动的高度
    private ArrayList<Fragment> fragments = new ArrayList<>();

    private CollegeIndexBean collegeIndexBean;//高校简介
    private ZhaoShengMessageBean zhaoShengMessageBean;//招生信息
    private AdminssionBean adminssionBean;//招生情况
    private TopicGroupBean topicGroupBean;//热门话题

    private Bundle bundle;

    private static final int GET_INFO = 10;
    private static final int FOCUS = 11;
    private static final int ZHAOSHENGMESSAGE = 12;
    private boolean zhaoShengMessageHasLoad = false;
    private static final int ZHAOSHENGSITUATION = 13;
    private boolean zhaoshengsituationHasLoad = false;
    private static final int TOPICGROUP = 14;
    private boolean topicgroupHasLoad = false;

    private int tabs_color, tabs_text_size, tabs_color_chosed;
    private boolean isChangePage = false;//是否已经到了最顶
    private final int SCROLL_TOP = 1;
    private final int SCROLL_BOTTOM = 2;
    private final int TAB_CLICK = 3;
    private final int SCROLL_BOTTOM1 = 4;

    private final int scrollSpeed = 4;//滑动速度

    private int current_item = 0;//当前选中item
    private final static int REQUEST_CODE = 0;

    private boolean changeFocus = false;

    private ErrorPageHandler myHandler = new ErrorPageHandler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS:
                    Gson gson = new Gson();
                    switch (msg.arg1) {
                        case GET_INFO://获取首页
                            CollegeIndexBean collegeIndexBean = gson.fromJson((String) msg.obj, CollegeIndexBean.class);
                            if (collegeIndexBean != null) {
                                if ("1".equals(collegeIndexBean.getShowcompinfo())) {
                                    final MyToFourFragmentDialog dialog = new MyToFourFragmentDialog(CollegeIndex.this, R.style.confirmDialog);
                                    dialog.show();
                                }
                                CollegeIndex.this.collegeIndexBean = collegeIndexBean;
                                CollegeIndexBean.CollegeBean college = collegeIndexBean.getCollege();
                                if (college != null) {
                                    MyImageLoader.showImage(college.getIcon(), college_index_icon);
                                    MyImageLoader.showImage(college.getBanner(), college_index_school_ima);
                                    college_name.setText(college.getSchool_name());
                                    //更新fragmentUI
                                    fg1.setOnLineAskBean(collegeIndexBean);
                                    fg2.setCollegeIndexBean(collegeIndexBean);
                                    //更新是否关注
                                    updateFocus(college);
                                }
                            }
                            break;
                        case ZHAOSHENGMESSAGE:
                            ZhaoShengMessageBean zhaoShengMessageBean = gson.fromJson((String) msg.obj, ZhaoShengMessageBean.class);
                            if (zhaoShengMessageBean != null) {
                                //更新fragmentUI
                                zhaoShengMessageHasLoad = true;
                                CollegeIndex.this.zhaoShengMessageBean = zhaoShengMessageBean;
                                fg3.setZhaoShengMessageBean(zhaoShengMessageBean);
                            }
                            break;
                        case FOCUS://关注
                            try {
                                JSONObject jsonObject = new JSONObject((String) msg.obj);
                                if (jsonObject != null) {
                                    String focus = jsonObject.getString("status");
                                    if ("1".equals(focus)) {
                                        college_index_focus.setText("已关注");
                                        college_index_focus.setBackgroundResource(R.drawable.shape_login_focusable);
                                    } else {
                                        //取消关注
                                        college_index_focus.setText("+关注");
                                        changeFocus = true;
                                        college_index_focus.setBackgroundResource(R.drawable.shape_login_unfocusable);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                        case ZHAOSHENGSITUATION://招生情况
                            AdminssionBean adminssionBean = gson.fromJson((String) msg.obj, AdminssionBean.class);
                            if (adminssionBean != null) {
                                zhaoshengsituationHasLoad = true;
                                CollegeIndex.this.adminssionBean = adminssionBean;
                                fg4.setZhaoShengSituationBean(adminssionBean);
                                if (CollegeIndex.this.collegeIndexBean != null) {
                                    fg4.setZhaoShengSituationCoverBean(CollegeIndex.this.collegeIndexBean);
                                }
                            }
                            break;
                        case TOPICGROUP://话题小组
                            TopicGroupBean topicGroupBean = gson.fromJson((String) msg.obj, TopicGroupBean.class);
                            if (topicGroupBean != null) {
                                topicgroupHasLoad = true;
                                CollegeIndex.this.topicGroupBean = topicGroupBean;
                                fg5.setTopicGroup(topicGroupBean);
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case SCROLL_TOP:
                    college_index_scroll.smoothScrollBy(0, scrollSpeed);
                    break;
                case SCROLL_BOTTOM:
                    college_index_scroll.smoothScrollBy(0, -scrollSpeed);
                    break;
                case TAB_CLICK:
                    setScrollView(SCROLL_TOP);
                    break;
                case SCROLL_BOTTOM1:
                    setScrollView(SCROLL_BOTTOM);
                    break;
                case ZhaoShengSituation.ONCLICK_ZHAOSHENGSITUATION:
                    setScrollView(SCROLL_TOP);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getIntent().getStringExtra("id");
        HashMap<String, String> hashMap = (HashMap<String, String>) getIntent().getSerializableExtra("params");//从baseActivity协议跳转得到的
        if (hashMap != null) {
            id = hashMap.get("id");
        }
        setViewPagerHeight();
        initData();
        initView();
        initTabStrip();
        getDataFromInternet();
    }

    private void initView() {
        college_index_back.setOnClickListener(this);
        college_index_focus.setOnClickListener(this);
        final MyListener myListener = new MyListener();
        college_index_scroll.setOnTouchListener(myListener);
        college_index_name.setText(getIntent().getStringExtra("name"));
        college_index_scroll.smoothScrollTo(0, 0);
        college_index_scroll.setScrollViewListener(new MyVolunteerScrollViewListener() {
            @Override
            public void onScrollChanged(MyVolunteerScrollView scrollView, int x, final int y, int oldx, int oldy) {
                if (y <= 0) {//完全透明
                    college_index_header.setBackgroundColor(Color.argb(0, 8, 130, 238));//AGB由相关工具获得，或者美工提供
                    college_index_name.setTextColor(Color.argb(0, 255, 255, 255));
                } else if (y > 0 && y <= (college_index_header_layout.getMeasuredHeight() - college_index_header.getMeasuredHeight())) {
                    float scale = (float) y / (college_index_header_layout.getMeasuredHeight() - college_index_header.getMeasuredHeight());
                    float alpha = (255 * scale);
                    // 只是layout背景透明(仿知乎滑动效果)
                    college_index_header.setBackgroundColor(Color.argb((int) alpha, 8, 130, 238));
                    college_index_name.setTextColor(Color.argb((int) alpha, 255, 255, 255));
                } else {//完全不透明
                    college_index_header.setBackgroundColor(Color.argb(255, 8, 130, 238));
                    college_index_name.setTextColor(Color.argb(255, 255, 255, 255));
                }
                if (!isChangePage) {
                    if (y == scrollDistance) {
                        bundle = new Bundle();
                        bundle.putInt("currentItem", current_item);
                        bundle.putString("id", getIntent().getStringExtra("id"));
                        bundle.putString("name", getIntent().getStringExtra("name"));
                        bundle.putSerializable("OnLineAsk", collegeIndexBean);
                        bundle.putSerializable("ZhaoShengMessage", zhaoShengMessageBean);
                        bundle.putSerializable("ZhaoShengSituation", adminssionBean);
                        bundle.putSerializable("TopicGroup", topicGroupBean);
                        final Intent i = new Intent();
                        i.setClass(CollegeIndex.this, CollegeMoreDetail.class);
                        i.putExtra("bundle", bundle);
                        startActivityForResult(i, REQUEST_CODE);
                        CollegeIndex.this.overridePendingTransition(0, 0);
                        isChangePage = true;
                    }
                }
                myListener.setY(y);
            }
        });
    }

    private class MyListener implements View.OnTouchListener {
        private int y;

        public void setY(int y) {
            this.y = y;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            boolean canScroll = false;
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    if (y >= (scrollDistance - 10)) {
                        setScrollView(SCROLL_TOP);
                        canScroll = true;
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (y >= (scrollDistance - 10)) {
                        canScroll = true;
                    }
                    break;
                default:
                    break;
            }
            return canScroll;
        }
    }

    private void initData() {
        tabs_color_chosed = this.getResources().getColor(R.color.common_color);
        tabs_color = this.getResources().getColor(R.color.tab_color);
        tabs_text_size = this.getResources().getDimensionPixelSize(R.dimen.text_size);
        fg1 = new OnLineAsk(this, id);
        fg2 = new CollegeIntroduce(this, myHandler);
        fg3 = new ZhaoShengMessageListView(this, id);
        fg4 = new ZhaoShengSituation(this, id, myHandler);
        fg5 = new TopicGroup(this, id, myHandler);
    }

    private void initTabStrip() {
        fragmentManager = this.getSupportFragmentManager();
        fragments.add(fg1);
        fragments.add(fg2);
        fragments.add(fg3);
        fragments.add(fg4);
        fragments.add(fg5);
        baseFragmentAdapter = new BaseFragmentAdapter(fragmentManager, fragments, tabs);
        college_index_pager.setOffscreenPageLimit(1);
        college_index_pager.setAdapter(baseFragmentAdapter);
        college_index_pager.setOffscreenPageLimit(fragments.size());
        college_index_strip.setTextColor(tabs_color);
        college_index_strip.setTextSize(tabs_text_size);
        college_index_strip.setDividerColor(Color.TRANSPARENT);
        college_index_strip.setDividerPadding(1);
        college_index_strip.setUnderlineHeight(0);
        college_index_strip.setIndicatorColor(tabs_color_chosed);
        college_index_strip.setIndicatorHeight(4);
        college_index_strip.setTabPaddingLeftRight(32);
        college_index_strip.setIndicatorPadding(30, 30);
        college_index_strip.setSelectedTextColor(tabs_color_chosed);
        college_index_strip.setViewPager(college_index_pager, myHandler);
        college_index_strip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                current_item = position;
                switch (position) {
                    case 0:
                        break;
                    case 1:

                        break;
                    case 2:
                        if (!zhaoShengMessageHasLoad) {
                            getZhaoShengMessageFromInternet(1);
                        }

                        break;
                    case 3:
                        if (!zhaoshengsituationHasLoad) {
                            getZhaoShengSituationFromInternet(Constant.DEFALUTE_PROV, Constant.DEFAULTE_TYPE, Constant.NO_MAJOR_FILTER, 1);
                        }
                        break;
                    case 4:
                        if (!topicgroupHasLoad) {
                            getTopicGroupFromInterNet(1);
                        }
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.college_index_back:
                Intent data = new Intent();
                data.putExtra("changeFocus", changeFocus);
                this.setResult(1, data);
                CollegeIndex.this.finish();
                break;
            case R.id.college_index_focus://关注
                focus();
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        Intent data = new Intent();
        data.putExtra("changeFocus", changeFocus);
        this.setResult(1, data);
        CollegeIndex.this.finish();
    }

    private void setScrollView(final int flag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < college_index_header.getMeasuredHeight(); i++) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = new Message();
                    message.what = flag;
                    myHandler.sendMessage(message);
                }
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isChangePage = false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE:
                if (resultCode != RESULT_CANCELED) {
                    switch (resultCode) {
                        case 1://高校更多返回
                            college_index_pager.setCurrentItem(data.getIntExtra("currentItem", 0), false);
                            TimerTask task = new TimerTask() {
                                @Override
                                public void run() {
                                    Message ms = new Message();
                                    ms.what = SCROLL_BOTTOM1;
                                    myHandler.sendMessage(ms);
                                    this.cancel();
                                }
                            };
                            Timer timer = new Timer();
                            timer.schedule(task, 100);
                            break;
                        default:
                            break;
                    }
                }
                break;
            default:
                break;
        }
    }

    private void updateFocus(CollegeIndexBean.CollegeBean college) {
        String focus = college.getIsattention();
        if ("1".equals(focus)) {
            college_index_focus.setText("已关注");
            college_index_focus.setBackgroundResource(R.drawable.shape_login_focusable);
        } else {
            college_index_focus.setText("+关注");
            college_index_focus.setBackgroundResource(R.drawable.shape_login_unfocusable);
        }
    }

    private void getDataFromInternet() {
        if (id != null) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("id", id);
            new InterNetController(CollegeIndex.this, Constant.COLLEGEDETAIL, myHandler, hashMap, GET_INFO);
        }
    }

    private void focus() {
        if (id != null) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("id", id);
            new InterNetController(CollegeIndex.this, Constant.COLLEGEATTENTION, myHandler, hashMap, FOCUS, false);
        }
    }

    private void getZhaoShengMessageFromInternet(int page) {
        if (id != null) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("college_id", id);
            hashMap.put("page", String.valueOf(page));
            new InterNetController(this, Constant.NEWLIST, myHandler, hashMap, ZHAOSHENGMESSAGE, false);
        }
    }

    private void getZhaoShengSituationFromInternet(String prov, String type, String major, int page) {
        if (id != null) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("id", id);
            if (!Constant.NO_MAJOR_FILTER.equals(major)) {
                hashMap.put("major", major);
            }
            hashMap.put("type", type);
            hashMap.put("prov", prov);
            hashMap.put("page", String.valueOf(page));
            new InterNetController(this, Constant.ADMISSION, myHandler, hashMap, ZHAOSHENGSITUATION, false);
        }
    }

    private void getTopicGroupFromInterNet(int page) {
        if (id != null) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("page", String.valueOf(page));
            hashMap.put("collegeid", id);
            new InterNetController(CollegeIndex.this, Constant.SHOWBLOG, myHandler, hashMap, TOPICGROUP, false);
        }
    }

    private void setViewPagerHeight() {
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        college_index_header_layout_parent.measure(w, h);
        college_index_header_layout.measure(w, h);
        college_index_header.measure(w, h);
        int headerParentHeight = college_index_header_layout_parent.getMeasuredHeight();
        WindowManager windowManager = this.getWindowManager();
        int windowHeight = windowManager.getDefaultDisplay().getHeight();
        final int leftHeght = windowHeight - headerParentHeight;
        int headerHeight = college_index_header_layout.getMeasuredHeight();
        scrollDistance = headerHeight - college_index_header.getMeasuredHeight();//可滑动的部分
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) college_index_pager.getLayoutParams();
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = leftHeght + scrollDistance;
        college_index_pager.setLayoutParams(params);
    }
}
